import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/http_constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/dialog/two_result_hint_dialog.dart';
import 'package:distribution_mall_flutter/entity/user/user_info_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/home/home_provider.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/provider/user/user_info.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:distribution_mall_flutter/widgets/icon_button.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:getwidget/getwidget.dart';
import 'package:webview_flutter/webview_flutter.dart';

class SideDrawer extends ConsumerStatefulWidget {
  const SideDrawer({
    super.key,
  });

  @override
  ConsumerState createState() => _SideDrawer();
}

class _SideDrawer extends ConsumerState<SideDrawer> {
  WebViewController? webViewController;
  String url = '';
  // bool googlePlayPackage = true;
  // String packageInstallSource = '';

  final TextStyle titleTextStyle = const TextStyle(
      fontSize: FontConstant.f16_4,
      color: Colors.black,
      letterSpacing: TextConstant.letterSpacing);

  @override
  void initState() {
    super.initState();
    // fun() async {
    //   googlePlayPackage = await Utils.isGooglePlayPackage();
    //   packageInstallSource = await Utils.packageInstallSource();
    //   setState(() {});
    // }

    // fun();
    if (!kIsWeb) {
      Map<String, String?> params = {...Utils.getUserParams()};
      url = '${HttpConstant.service}?${Uri(queryParameters: params).query}';
      webViewController = WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..loadRequest(Uri.parse(HttpConstant.service))
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {},
            onPageStarted: (String url) {},
            onPageFinished: (String url) {},
            onHttpError: (HttpResponseError error) {},
            onWebResourceError: (WebResourceError error) {},
            // onNavigationRequest: (NavigationRequest request) {
            //   if (request.url.startsWith('https://www.youtube.com/')) {
            //     return NavigationDecision.prevent;
            //   }
            //   return NavigationDecision.navigate;
            // },
          ),
        )
        ..reload();
    }
  }

  Widget renderHeader(BuildContext context) {
    return Consumer(builder: (context, ref, widget) {
      UserDisplayEntity? userInfo =
          ref.watch(userInfoProvider.select((value) => value.userInfo));
      bool isLogin = ref.watch(loginStateProvider);
      if (isLogin) {
        String? nick = EPstorage.userInfo.get(UserInfoBoxKey.nick);
        return Container(
          height: 163,
          width: double.infinity,
          padding: const EdgeInsets.fromLTRB(
              EdgeConstant.edge218, 86.5, EdgeConstant.edge218, 25),
          decoration: const BoxDecoration(
              border: Border(
                  bottom:
                      BorderSide(color: ColorConstant.grey233_4, width: 0.9))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Dear',
                style: TextStyle(
                    fontSize: FontConstant.f146,
                    color: Colors.black,
                    letterSpacing: TextConstant.letterSpacing),
              ),
              const SizedBox(
                height: 7,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                      child: Text(
                    nick ?? userInfo?.nickName ?? '',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                        fontSize: 18.2,
                        fontWeight: FontWeight.bold,
                        letterSpacing: TextConstant.letterSpacing,
                        color: Colors.black),
                  )),
                  EPIconButton(
                      onPressed: () {
                        ///弹出提示弹框
                        showDialog(
                            context: context,
                            builder: (_) => const TwoResultHintDialog(
                                title: 'Do you want to log out?',
                                rightText: 'Exit')).then((bol) {
                          if (bol == true) {
                            Navigator.pop(context);
                            ref
                                .watch(loginStateProvider.notifier)
                                .outLogin(go2login: false);
                          }
                        });
                      },
                      iconColor: Colors.black,
                      icon: ImageLoader.imageAsset(
                        ImageLocalConstant.outputRight,
                      ),
                      commonWH: EdgeConstant.edge146)
                ],
              )
            ],
          ),
        );
      }
      return Container(
        height: 161.1,
        padding: const EdgeInsets.fromLTRB(EdgeConstant.edge218, 45,
            EdgeConstant.edge218, EdgeConstant.edge10),
        decoration: const BoxDecoration(
            border: Border(
                bottom:
                    BorderSide(color: ColorConstant.grey233_4, width: 0.9))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.only(bottom: EdgeConstant.edge218),
              child: DefaultTextStyle(
                  style: const TextStyle(
                      color: Colors.black,
                      fontSize: FontConstant.f16_4,
                      letterSpacing: TextConstant.letterSpacing),
                  child: Column(
                    children: [
                      Text(S.current.home_log_detail1),
                      Text(S.current.home_log_detail2),
                    ],
                  )),
            ),
            CommonBtnWidget.generalBtn(() {
              Navigator.pop(context);
              ref.read(loginStateProvider.notifier).outLogin(go2login: true);
              // appRouter.push(const LoginRoute());
            },
                width: 175.7,
                height: 38.2,
                text: S.current.log_in_now,
                shape: GFButtonShape.square)
          ],
        ),
      );
    });
  }

  Widget renderListTile({
    required Function() onTap,
    required String text,
    required String img,
    bool hasRoot = true,
    double commonWH = EdgeConstant.edge218,
  }) {
    return ListTile(
        onTap: () {
          onTap();
          // FirebaseAnalyticsUtils.logEvent(
          //     name: PointConstant.hpSideMenu, parameters: {'tagName': text});
        },
        minTileHeight: 50,
        contentPadding:
            const EdgeInsets.symmetric(horizontal: EdgeConstant.edge218),
        leading:
            ImageLoader.imageAsset(img, commonWH: commonWH, hasRoot: hasRoot),
        titleTextStyle: titleTextStyle,
        title: Transform.translate(
          offset: const Offset(-10, 0), // 调整title的位置
          child: Text(text),
        ));
  }

  @override
  Widget build(BuildContext context) {
    bool isLogin = ref.watch(loginStateProvider);
    String curTitleVersion =
        ref.watch(appInfoProvider.select((value) => value.curTitleVersion));
    return Drawer(
      width: 219.4,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.zero,
      ),
      backgroundColor: Colors.white,
      child: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          // fit: StackFit.expand,
          children: [
            Positioned.fill(
                child: Container(
                    decoration: const BoxDecoration(
                        gradient: LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                  Color.fromRGBO(245, 246, 248, 1),
                  Color.fromRGBO(255, 255, 255, 1),
                  Color.fromRGBO(255, 255, 255, 1),
                  // Colors.black,
                  // Colors.black,
                ],
                            stops: [
                  0,
                  0.38,
                  0.38,
                ])))),
            DefaultTextStyle(
              style: const TextStyle(
                  color: Colors.black,
                  fontSize: FontConstant.f16_4,
                  letterSpacing: TextConstant.letterSpacing),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  renderHeader(context),
                  Expanded(
                      child: ListView(padding: EdgeInsets.zero, children: [
                    renderListTile(
                        onTap: () {
                          appRouter.push(const OrderListRoute());
                        },
                        text: S.current.my_myOrder,
                        img: ImageLocalConstant.order),
                    renderListTile(
                        onTap: () {
                          appRouter.push(const AgreementRoute());
                        },
                        text: S.current.legal_policies,
                        img: ImageLocalConstant.policies),
                    renderListTile(
                        onTap: () {
                          Utils.go2Page(() {
                            appRouter.push(ServiceRoute(
                              webViewController: webViewController,
                            ));
                          }, url: url);
                        },
                        text: S.current.contact_us,
                        hasRoot: false,
                        img: Assets.assets_icons_home_side_service_png),
                    isLogin
                        ? renderListTile(
                            onTap: () async {
                              bool? result = await showDialog(
                                  context: context,
                                  builder: (_) => TwoResultHintDialog(
                                      title:
                                          S.current.home_account_deletion_tip));
                              if (result != true) return;
                              appRouter.push(const DeleteAccountNoticeRoute());
                            },
                            commonWH: 18.2,
                            text: S.current.home_account_deletion,
                            img: Assets
                                .assets_icons_delete_account_delete_user_png,
                            hasRoot: false)
                        : const SizedBox.shrink(),
                    renderListTile(
                        onTap: () async {
                          appRouter.push(const MerchantAuthenticationRoute());
                        },
                        text: S.current.authentication,
                        img: Assets
                            .assets_icons_account_merchant_uthentication_png,
                        hasRoot: false),
                  ])),
                  if (!kIsWeb)
                    Container(
                      alignment: Alignment.bottomCenter,
                      padding: EdgeInsets.only(
                          bottom: 29 + MediaQuery.of(context).padding.bottom),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 56.4,
                            height: 0.9,
                            color: const Color.fromRGBO(238, 238, 238, 1),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 7),
                            child: Text(
                              'V$curTitleVersion',
                              style: const TextStyle(
                                  color: Color.fromRGBO(134, 141, 150, 1),
                                  fontSize: 10.9,
                                  fontWeight: FontWeight.w400,
                                  letterSpacing: -0.3),
                            ),
                          ),
                          Container(
                            width: 56.4,
                            height: 0.9,
                            color: const Color.fromRGBO(238, 238, 238, 1),
                          ),
                        ],
                      ),
                    )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
